package com.xgp.microChat.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.internet.MimeMessage;

@Api(tags = "邮件相关")
@RestController
@RequestMapping("/mail")
public class MailController {

    @Autowired
    JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String sendEmail;

    @ApiOperation("发送邮件的方法")
    @PostMapping("/sendEmail")
    public boolean sendEmail(@ApiParam("邮件接受者的邮件") @RequestParam("email") String email,  //接受者账号
                             @ApiParam("需要发送的信息") @RequestParam("msg") String msg) {    //发送的消息
        try {
            final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
            final MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setFrom(sendEmail);
//            System.out.println(email);
            if(email != null && msg != null) {
                message.setTo(email);
                message.setSubject("微聊——为简化开发而生");
                message.setText(msg,true);

                mailSender.send(mimeMessage);
                return true;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }
}
